package com.sky.controller.user;


import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "用户地址接口")
public class AddressController {

    @Autowired
    AddressService addressService;

    @PostMapping
    @ApiOperation("新增地址")
    public Result<String> addNewAddress(@RequestBody AddressBook addressBook) {
        addressService.save(addressBook);
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("查询当前用户地址簿")
    public Result<List<AddressBook>> requestAddress() {
        return Result.success(addressService.requestAddress(0));
    }

    @GetMapping("/default")
    @ApiOperation("查询当前默认地址")
    public Result<AddressBook> requestDefaultAddress() {
        List<AddressBook> list = addressService.requestAddress(1);
        if(list == null){
            return Result.error("无默认地址");
        }
        else{
            return Result.success(list.get(0));
        }
    }

    @PutMapping
    @ApiOperation("修改地址")
    public Result<String> updateAddress(@RequestBody AddressBook addressBook){
        addressService.updateAddress(addressBook);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据地址id查询地址")
    public Result<AddressBook> getAddress(@PathVariable Long id){
        return Result.success(addressService.getAddress(id));
    }

    @DeleteMapping
    @ApiOperation("删除地址")
    public Result<AddressBook> deleteAddress(Long id){
        addressService.deleteAddress(id);
        return Result.success();
    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result<String> setDefalutAddress(@RequestBody AddressBook addressBook){
        addressService.setDefalutAddress(addressBook.getId());
        return Result.success();
    }

}
